package com.yex.service.modify.bank;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yex.common.exception.RRException;
import com.yex.dao.BankDao;
import com.yex.entity.BankEntity;
import com.yex.entity.UserEntity;
import com.yex.service.BankListService;
import com.yex.service.modify.BaseService;
import com.yex.util.CommonModifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(value = "modify_bank_service")
@Transactional
public class BankService extends BaseService<BankDao, BankEntity> {

    @Autowired
    private BankListService bankListService;

    /**
     * 是否为当前登录用户的银行卡
     *
     * @param bankEntity
     * @return
     */
    private BankEntity _checkSelf(BankEntity bankEntity) {
        EntityWrapper<BankEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper
                .where("id = {0}", bankEntity.getId())
                .andNew("user_id = {0}", bankEntity.getUserId());
        List<BankEntity> exists = baseMapper.selectList(entityWrapper);
        if (exists != null && exists.size() <= 0) throw new RRException("无效的银行卡信息");
        return exists.get(0);
    }

    /**
     * 银行卡是否已存在
     *
     * @param bankEntity
     * @param id
     */
    private void _checkExists(BankEntity bankEntity, Integer id, Integer userId) {
        EntityWrapper<BankEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper
                .eq("name", bankEntity.getName())
                .eq("card_number", bankEntity.getCardNumber())
                .eq("branch_address", bankEntity.getBranchAddress())
                .eq("address", bankEntity.getAddress())
                .eq("bank", bankEntity.getBank())
                .eq("user_id", userId);
        if (id != 0) entityWrapper.ne("id", id);
        List<BankEntity> exists = baseMapper.selectList(entityWrapper);
        if (exists != null && exists.size() > 0) throw new RRException("该银行卡已经被绑定");
    }

    /**
     * 更新银行卡信息
     *
     * @param bankEntity
     * @param request
     */
    private void _update(BankEntity bankEntity, HttpServletRequest request) {
        UserEntity userEntity = validateLoginUser(request);
        bankEntity.setUserId(userEntity.getId());
        _checkSelf(bankEntity);
        _checkExists(bankEntity, bankEntity.getId(), userEntity.getId());
        bankEntity.setUpdateTime(new Date());
        EntityWrapper<BankEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("id", bankEntity.getId()).eq("user_id", userEntity.getId());
        Integer count = baseMapper.update(bankEntity, wrapper);
        if (count > 1) throw new RRException("修改银行卡信息失败");
    }

    /**
     * 得到当前登录用户的银行卡信息
     *
     * @return
     */
    public List<BankEntity> findByMyList() {
        UserEntity userEntity = validateLoginUser(CommonModifyUtil.getRequest());
        EntityWrapper<BankEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userEntity.getId()).eq("status", 1);
        List<BankEntity> list = baseMapper.selectList(wrapper);
        for (BankEntity item : list) {
            item.setBankListEntity(bankListService.findById(item.getBank()));
        }
        return list;
    }

    /**
     * 新增一张银行卡
     *
     * @param bankEntity
     * @param request
     */
    public void add(BankEntity bankEntity, HttpServletRequest request) {
        List<BankEntity> bankEntities = findByMyList();
        if (bankEntities != null && bankEntities.size() > 0) throw new RRException("已有银行卡,请勿重新绑定");
        UserEntity userEntity = validateLoginUser(request);
        if (!bankEntity.getName().equalsIgnoreCase(userEntity.getRealName())) throw new RRException("开户名必须与实名认证的名称一致");
        bankEntity.setUserId(userEntity.getId());
        _checkExists(bankEntity, 0, userEntity.getId());
        bankEntity.setIsDefault(0);
        baseMapper.insert(bankEntity);
    }

    /**
     * 对外提供更新服务
     *
     * @param bankEntity
     * @param request
     */
    public void update(BankEntity bankEntity, HttpServletRequest request) {
        bankEntity.setStatus(null);
        bankEntity.setIsDefault(null);
        bankEntity.setCreateTime(null);
        _update(bankEntity, request);
    }


    public void delete(Integer id, HttpServletRequest request) {
        BankEntity bankEntity = new BankEntity();
        bankEntity.setId(id);
        bankEntity.setStatus(0);
        _update(bankEntity, request);
    }

    /**
     * 设置默认银行卡
     *
     * @param id
     * @param request
     */
    public void setDefault(Integer id, HttpServletRequest request) {
        UserEntity userEntity = validateLoginUser(request);
        EntityWrapper<BankEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", userEntity.getId());
        BankEntity bankEntity = new BankEntity();
        bankEntity.setIsDefault(0);
        baseMapper.update(bankEntity, wrapper);
        wrapper.eq("id", id);
        bankEntity.setIsDefault(1);
        baseMapper.update(bankEntity, wrapper);
    }

    public BankEntity getDefaultBank() {
//        UserEntity userEntity = validateLoginUser(CommonModifyUtil.getRequest());
        List<BankEntity> bankEntities = findByMyList();
        if (bankEntities == null || bankEntities.size() == 0) throw new RRException("请先绑定银行卡");
        if (bankEntities.size() != 1) throw new RRException("每个用户只能绑定一张银行卡");
        BankEntity defaultBank = null;
        for (BankEntity item : bankEntities) {
            if (item.getIsDefault() == 1) defaultBank = item;
        }
        if (defaultBank == null) defaultBank = bankEntities.get(0);
        if (defaultBank == null) throw new RRException("请先绑定银行卡");
        return defaultBank;
    }

    public BankEntity findDataById(Integer id) {
        EntityWrapper<BankEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id).eq("status", 1);
        List<BankEntity> bankEntities = baseMapper.selectList(wrapper);
        if (bankEntities == null || bankEntities.size() == 0) return null;
        BankEntity bankEntity = bankEntities.get(0);
        bankEntity.setBankListEntity(bankListService.findById(bankEntity.getBank()));
        return bankEntities.get(0);
    }

}
